package cn.lyvust.eais.manage.controller;

import cn.lyvust.eais.common.annotation.SysLogs;
import cn.lyvust.eais.common.bean.ResponseCode;
import cn.lyvust.eais.common.bean.ResponseResult;
import cn.lyvust.eais.common.exception.RequestException;
import cn.lyvust.eais.common.util.BeansUtil;
import cn.lyvust.eais.manage.dto.param.FindRoleParam;
import cn.lyvust.eais.manage.dto.param.rank.StudentAddParam;
import cn.lyvust.eais.manage.dto.param.rank.StudentExcelDTO;
import cn.lyvust.eais.manage.dto.param.rank.StudentParam;
import cn.lyvust.eais.manage.entity.Student;
import cn.lyvust.eais.manage.service.StudentService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ggzheng
 * @since 2021-04-04
 */
@RequestMapping("/rank/student")
@RestController
@Api(tags = {"招生管理"})
public class StudentController {
    @Autowired
    private StudentService service;

    @ApiOperation("分页获取招生数据")
    @PostMapping("/list")
    public ResponseResult list(@RequestBody @Validated @ApiParam(value = "用户获取过滤条件") StudentParam dto){
        QueryWrapper wrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(dto.getPhone())) {
            wrapper.eq("phone", dto.getPhone());
        }
        if (StringUtils.isNotEmpty(dto.getCertNo())) {
            wrapper.eq("cert_no", dto.getCertNo());
        }
        if (StringUtils.isNotEmpty(dto.getStuNo())) {
            wrapper.eq("stu_no", dto.getStuNo());
        }
        if (StringUtils.isNotEmpty(dto.getUsername())) {
            wrapper.eq("username", dto.getUsername());
        }
        if (StringUtils.isNotEmpty(dto.getTeacherName())) {
            wrapper.eq("teacher_name", dto.getTeacherName());
        }
        wrapper.orderByDesc("update_time");
        return ResponseResult.e(ResponseCode.OK,service.page(new Page<>(dto.getPage(), dto.getPageSize()), wrapper));
    }

    @ApiOperation("新增一个招生信息")
    @PostMapping("/add")
    //    @RequiresPermissions("rank:student:add")
    @SysLogs("添加一个招生数据")
    public ResponseResult add(@RequestBody @Validated @ApiParam(value = "用户获取过滤条件") StudentAddParam dto){
        return ResponseResult.e(ResponseCode.OK,service.add(dto));
    }

    @ApiOperation("修改一个招生信息")
    @PostMapping("/update")
    //    @RequiresPermissions("rank:student:update")
    @SysLogs("修改一个招生数据")
    public ResponseResult update(@RequestBody @Validated @ApiParam(value = "用户获取过滤条件") StudentParam dto){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", dto.getUsername());
        List resList = service.list(wrapper);
        if (resList == null || resList.size() == 0) {
            throw RequestException.fail("学生信息不存在!");
        }
        if (resList.size() >= 2 && StringUtils.isEmpty(dto.getCertNo())) {
            throw RequestException.fail("学生重名,请输入学生的身份证号码!");
        }
        if (StringUtils.isNotEmpty(dto.getCertNo())) {
            wrapper.eq("cert_no", dto.getCertNo());
        }
        resList = service.list(wrapper);
        if (resList.size() == 1) {
            Student entity = (Student) resList.get(0);
            BeansUtil.copyPropertiesIgnoreNull(dto, entity);
            service.updateById(entity);
        } else {
            throw RequestException.fail("修改失败,请联系管理员!");
        }
        return ResponseResult.e(ResponseCode.OK);
    }

    @ApiOperation("删除一个招生信息")
    @PostMapping("/delete")
    //    @RequiresPermissions("rank:student:delete")
    @SysLogs("删除一个招生数据")
    public ResponseResult delete(@RequestBody @Validated @ApiParam(value = "用户获取过滤条件") StudentParam dto){
        return ResponseResult.e(ResponseCode.OK, service.del(dto));
    }
    @GetMapping(value = {"/export"})
    @ApiOperation(value = "导出所有招生明细")
    @SysLogs("导出所有招生明细")
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
//            String exportTpe = request.getParameter("type");
            String fileName = URLEncoder.encode("招生明细", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            List resList = service.list();
            if (resList == null) {
                return;
            }
            List<StudentExcelDTO> excelData = new ArrayList<>();
            resList.forEach(item -> {
                Student object = (Student)item;
                System.out.println(item);
                StudentExcelDTO dto = new StudentExcelDTO();
                dto.setUserName(object.getUsername());
                dto.setTeacherName(object.getTeacherName());
                dto.setTeacherNo(object.getTeacherNo());
                dto.setCertNo(object.getCertNo());
                dto.setMajor(object.getMajor());
                dto.setSchool(object.getSchool());
                dto.setPhone(object.getPhone());
                dto.setAddInfo(object.getAddInfo());
                dto.setCreateTime(object.getCreateTime());
                excelData.add(dto);
            });
            excelData.sort(Comparator.comparing(StudentExcelDTO::getTeacherName));

//            EasyExcel.write(response.getOutputStream(), StudentExcelDTO.class)
//                    .sheet("模板").doWrite(excelData);

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            // 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").needHead(Boolean.FALSE).build();
            // 这里必须指定需要头，table 会继承sheet的配置，sheet配置了不需要，table 默认也是不需要
            WriteTable writeTable = EasyExcel.writerTable(0).head(StudentExcelDTO.class).
                    needHead(Boolean.TRUE).build();
            // 第一次写入会创建头
            excelWriter.write(excelData, writeSheet, writeTable);
            // 千万别忘记finish 会帮忙关闭流
            excelWriter.finish();
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}
